package com.hzit.servlet.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.UUID;

@WebServlet(name = "AServlet",urlPatterns = "/cookie/aservlet")
public class AServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建cookie



        String id = UUID.randomUUID().toString(); //生成随机的字符串 （唯一）
        Cookie cookie1 = new Cookie("id", id);
        cookie1.setPath(req.getContextPath()); //设置路径范围
        cookie1.setMaxAge(60*60*24*7); //设置有效时间

        Cookie cookie2 = new Cookie("lasttime", new Date().toString());
        cookie2.setPath(req.getContextPath());

        Cookie cookie3 = new Cookie("username", URLEncoder.encode("张三","utf-8"));
        cookie3.setPath(req.getContextPath());


        resp.addCookie(cookie1);
        resp.addCookie(cookie2);
        resp.addCookie(cookie3);

        resp.getWriter().println("cookie创建成功,发送给客户端浏览器:" + id);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
